package com.baseframe.gateway.router;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.baseframe.launch.constant.BaseNacosConstant;
import com.baseframe.launch.props.BaseProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executor;

@Slf4j
@Component
public class BaseRouterHandlerListener {

    private final NacosDiscoveryProperties nacosDiscoveryProperties;
    private final NacosConfigProperties nacosConfigProperties;
    private final BaseProperties baseProperties;

    private final BaseRouterHandler baseRouterHandler;

    public BaseRouterHandlerListener(NacosDiscoveryProperties nacosDiscoveryProperties, NacosConfigProperties nacosConfigProperties, BaseProperties baseProperties, BaseRouterHandler baseRouterHandler) {
        this.nacosDiscoveryProperties = nacosDiscoveryProperties;
        this.nacosConfigProperties = nacosConfigProperties;
        this.baseProperties = baseProperties;
        this.baseRouterHandler = baseRouterHandler;

        this.routeHandlerListener();

    }

    private void routeHandlerListener(){

        try {
            String dataId = BaseNacosConstant.dataId(baseProperties.getProfilesEnv(),baseProperties.getApplicationName(),"json");
            String group = nacosConfigProperties.getGroup();
            //创建配置文件
            Properties properties = new Properties();
            properties.setProperty(PropertyKeyConst.SERVER_ADDR, nacosDiscoveryProperties.getServerAddr());
            properties.setProperty(PropertyKeyConst.NAMESPACE, nacosDiscoveryProperties.getNamespace());
            //创建配置
            ConfigService configService = NacosFactory.createConfigService(properties);

            configService.addListener(dataId, group, new Listener() {
                @Override
                public Executor getExecutor() {
                    return null;
                }

                @Override
                public void receiveConfigInfo(String configInfo) {
                    //将配置信息json转换成对象集合
                    List<RouteDefinition> routeDefinitions = JSON.parseArray(configInfo, RouteDefinition.class);
                    baseRouterHandler.updateList(routeDefinitions);
                }
            });

        }catch (NacosException e){
            log.error("DynamicRouteServiceListener.dynamicRouteServiceListener()动态路由监听器发生了异常:{}",e.getMessage(),e);
        }
    }


}
